﻿/**********************************************************
 ●项目：Smartkernel
 ●公司：智能核心信息技术研发中心
 ●作者：曹艳白
 ●邮箱：caoyanbai@gmail.com
 ●创建：2008-08-10
 ●版本：1.0
**********************************************************/
using System.Data;
using System.IO;
using System.Text;

namespace Smartkernel.Extensions
{
    /// <summary>
    /// DataTable的扩展
    /// </summary>
    public static class SmartDataTableExtension
    {
        /// <summary>
        /// 得到数据表中指定列的最大值
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="columnName">列名称</param>
        /// <returns>最大值</returns>
        public static double Max(this DataTable dataTable, string columnName)
        {
            DataRow[] dataRows = dataTable.Select(columnName + " IS NOT NULL", columnName + " DESC");
            return double.Parse(dataRows[0][columnName].ToString());
        }
        /// <summary>
        /// 得到数据表中指定列的最小值
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="columnName">列名称</param>
        /// <returns>最小值</returns>
        public static double Min(this DataTable dataTable, string columnName)
        {
            DataRow[] dataRows = dataTable.Select(columnName + " IS NOT NULL", columnName + " ASC");
            return double.Parse(dataRows[0][columnName].ToString());
        }
        /// <summary>
        /// 得到数据表中指定列的平均值（Null的列也算为平均的范围）
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="columnName">列名称</param>
        /// <returns>平均值</returns>
        public static double Avg(this DataTable dataTable, string columnName)
        {
            return Sum(dataTable, columnName) / dataTable.Rows.Count;
        }
        /// <summary>
        /// 得到数据表中指定列的和
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="columnName">列名称</param>
        /// <returns>和</returns>
        public static double Sum(this DataTable dataTable, string columnName)
        {
            DataRow[] dataRows = dataTable.Select(columnName + " IS NOT NULL");
            double sum = 0;
            foreach (var dataRow in dataRows)
            {
                sum = sum + int.Parse(dataRow[columnName].ToString());
            }
            return sum;
        }
          /// <summary>
        /// 保存成CSV格式的文件
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="filePath">要保存的路径</param>
        public static void SaveToCSV(this DataTable dataTable, string filePath)
        {
            SaveToCSV(dataTable, filePath, Encoding.Default);
        }
        /// <summary>
        /// 保存成CSV格式的文件
        /// </summary>
        /// <param name="dataTable">待处理的数据表</param>
        /// <param name="filePath">要保存的路径</param>
        /// <param name="encoding">编码方式</param>
        public static void SaveToCSV(this DataTable dataTable, string filePath, Encoding encoding)
        {
            StringBuilder csv = new StringBuilder();
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                string value = dataTable.Columns[i].ColumnName;
                if (i == dataTable.Columns.Count - 1)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        csv.Append("\"" + value.Replace("\"", "\"\"") + "\"\r\n");
                    }
                    else
                    {
                        csv.Append("\r\n");
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        csv.Append("\"" + value.Replace("\"", "\"\"") + "\"\t");
                    }
                    else
                    {
                        csv.Append("\"\"\t");
                    }
                }
            }
            foreach (DataRow dataRow in dataTable.Rows)
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    string value = dataRow[dataTable.Columns[i].ColumnName].ToString();
                    if (i == dataTable.Columns.Count - 1)
                    {
                        if (!string.IsNullOrEmpty(value))
                        {
                            csv.Append("\"" + value.Replace("\"", "\"\"") + "\"\r\n");
                        }
                        else
                        {
                            csv.Append("\r\n");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(value))
                        {
                            csv.Append("\"" + value.Replace("\"", "\"\"") + "\"\t");
                        }
                        else
                        {
                            csv.Append("\"\"\t");
                        }
                    }
                }
            }
            using (StreamWriter writer = new StreamWriter(filePath, false, encoding))
            {
                writer.Write(csv.ToString());
                writer.Flush();
            }
        }
    }
}
